﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Attendences.Framework.Entity;
using Attendences.Framework.BusinessLogic;
using Wicresoft.Common;
using Wicresoft.Framework.Organization;

public partial class Page_EditAttendencesList : BaseAuthenticationPage
{
    protected DataTable ItemList
    {
        get
        {
            if (ViewState["ItemList"] == null)
            {
                DataTable dt = DataAccess.ExecuteSql("Attendences.ConnectionString", "select top 1 * from AttendenceItem").Tables[0];
                dt.Columns.Add("aIndex", typeof(int));
                dt.Columns.Add("UserID", typeof(string));
                dt.Columns.Add("UserName", typeof(string));
                dt.Columns.Add("UserDisplayName", typeof(string));
                dt.Columns.Add("DepartmentID", typeof(string));
                dt.Columns.Add("OtherUserID", typeof(string));
                dt.Columns.Add("OtherUserName", typeof(string));
                dt.Columns.Add("Remark2", typeof(string));
                ViewState["ItemList"] = dt.Clone();
            }
            return ViewState["ItemList"] as DataTable;
        }
        set
        {
            ViewState["ItemList"] = value;
        }
    }

    protected DataTable DelItem
    {
        get
        {
            if (ViewState["DelItem"] == null)
                ViewState["DelItem"] = new DataTable();
            return ViewState["DelItem"] as DataTable;
        }
        set
        {
            ViewState["DelItem"] = value;
        }
    }

    public int AttendID
    {
        get
        {
            if (Request.QueryString["ID"] != null)
                return int.Parse(Request.QueryString["ID"]);
            return 0;
        }
    }

    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }
    private void InitControl()
    {
        for (int i = 0; i < 24; i++)
        {
            ddlStartHour.Items.Add(i.ToString("D2"));
            ddlEndHour.Items.Add(i.ToString("D2"));
        }
        for (int i = 0; i < 60; i += 5)
        {
            ddlStartMinute.Items.Add(i.ToString("D2"));
            ddlEndMinute.Items.Add(i.ToString("D2"));
        }
        ddlWeek.DataSource = new Week[] { new Week("全部","全部"), new Week("星期一",DayOfWeek.Monday.ToString()),
                                          new Week("星期二",DayOfWeek.Tuesday.ToString()), new Week("星期三",DayOfWeek.Wednesday.ToString()),
                                          new Week("星期四",DayOfWeek.Thursday.ToString()), new Week("星期五",DayOfWeek.Friday.ToString()),
                                          new Week("星期六",DayOfWeek.Saturday.ToString()), new Week("星期天",DayOfWeek.Sunday.ToString()) };
        ddlWeek.DataTextField = "Text";
        ddlWeek.DataValueField = "Value";
        ddlWeek.DataBind();

        DataTable dtType = Helper.GetAttendenceType();
        rpType2.DataSource = dtType;
        rpType2.DataTextField = "Name";
        rpType2.DataValueField = "ID";
        rpType2.DataBind();

        rpType2.Items.Insert(0, new ListItem("请选择", ""));

        rpType.DataSource = dtType;
        rpType.DataTextField = "Name";
        rpType.DataValueField = "ID";
        rpType.DataBind();

        rpType.Items.Insert(0, new ListItem("请选择", ""));

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "值班添加";
        this.tbAttendDate.Attributes.Add("readonly", "true");
        this.txtUserID.Attributes.Add("readonly", "true");
        this.txtUserName.Attributes.Add("readonly", "true");
        this.txtUserDisplayName.Attributes.Add("readonly", "true");
        this.txtPLUserID.Attributes.Add("readonly", "true");
        this.txtPLUserName.Attributes.Add("readonly", "true");
        this.txtPLUserDisplayName.Attributes.Add("readonly", "true");
        txtOtherUserDisplay.Attributes.Add("readonly", "true");
        txtOtherUserID.Attributes.Add("readonly", "true");
        txtPLOtherUserDisplay.Attributes.Add("readonly", "true");
        tbPlace.Attributes.Add("onkeyup", "getPlace(this.value);");

        if (!IsPostBack)
        {
            InitControl();
            if (AttendID != 0)
            {
                this.Title = "值班编辑";
                Attendence attendence = new Attendence(AttendID);
                attendence.Load();
                //if (attendence.IsShutDown == true)
                //{
                //    ClientScript.RegisterStartupScript(GetType(), "aWarning", "<script>alert('该值班未发布，不能修改！');window.opener = null;window.open('','_self');window.close();</script>");
                //}
                tbName.Text = attendence.Name;
                tbName.Enabled = false;
                tbPlace.Text = attendence.Place;
                tbPlace.Enabled = false;
                tbDescription.Text = attendence.Description;
                tbDescription.Enabled = false;

                lbtnSave.Text = "<span><img src=\"../Images/Icon/Object/Dataset-add.gif\" /></span><span>保存</span>";

                //取出当前AttendID对应的表AttendenceItem中的集合,保存在ItemList中
                DataTable dtType = DataAccess.SelectAll(typeof(AttendenceType));
                ItemList = BLAttendences.GetAttendenceItem(string.Format("{0}={1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
                ItemList.Columns.Add("UserID", typeof(string));
                ItemList.Columns.Add("UserName", typeof(string));
                ItemList.Columns.Add("UserDisplayName", typeof(string));
                ItemList.Columns.Add("aIndex", typeof(int));
                ItemList.Columns.Add("DepartmentID", typeof(string));
                ItemList.Columns.Add("OtherUserID", typeof(string));
                ItemList.Columns.Add("OtherUserName", typeof(string));
                ItemList.Columns.Add("Remark2", typeof(string));
                int i = 0;
                foreach (DataRow dr in ItemList.Rows)
                {
                    DataTable dtUser = BLAttendences.GetAttendenceUser("AttendenceItemID = '" + dr["ID"].ToString() + "'");
                    ArrayList UserID = new ArrayList();
                    ArrayList UserName = new ArrayList();
                    ArrayList UserDisplayName = new ArrayList();
                    ArrayList UserDeptID = new ArrayList();
                    ArrayList OtherUserID = new ArrayList();
                    ArrayList OtherUserName = new ArrayList();
                    foreach (DataRow drUser in dtUser.Rows)
                    {
                        if (drUser["UserType"].ToString() == UserType.Portal.ToString())
                        {
                            UserID.Add(drUser["UserID"].ToString());
                            UserName.Add(drUser["UserName"].ToString());
                            UserDisplayName.Add(drUser["UserDisplayName"].ToString());
                            UserDeptID.Add(drUser["DepartmentID"].ToString());
                        }
                        else if (drUser["UserType"].ToString() == UserType.Other.ToString())
                        {
                            OtherUserID.Add(drUser["UserID"].ToString());
                            OtherUserName.Add(drUser["UserName"].ToString());
                        }
                    }
                    dr["UserID"] = string.Join(";", UserID.ToArray(typeof(string)) as string[]);
                    dr["UserName"] = string.Join(";", UserName.ToArray(typeof(string)) as string[]);
                    dr["UserDisplayName"] = string.Join(";", UserDisplayName.ToArray(typeof(string)) as string[]);
                    dr["DepartmentID"] = string.Join(";", UserDeptID.ToArray(typeof(string)) as string[]);
                    dr["OtherUserID"] = string.Join(";", OtherUserID.ToArray(typeof(string)) as string[]);
                    dr["OtherUserName"] = string.Join(";", OtherUserName.ToArray(typeof(string)) as string[]);
                    dr["aIndex"] = i;
                    i++;

                    DataRow[] dr2s = dtType.Select("ID='" + dr["Remark"].ToString() + "'");
                    if (dr2s.Length > 0)
                    {
                        dr["remark2"] = dr2s[0]["Name"].ToString();

                    }
                }
                DelItem = ItemList.Clone();
                BindRptItemList();
            }
        }
    }

    protected void btnAddItem_Click(object sender, EventArgs e)
    {
        if (tbAttendDate.Text.Trim() == string.Empty)
        {
            string script = "<script>alert('必须填写值班日期和值班时间!');</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "Alert", script);
            return;
        }

        DataRow dr = ItemList.NewRow();
        dr["aIndex"] = ItemList.Rows.Count + 1;
        dr["AttendDate"] = DateTime.Parse(tbAttendDate.Text);
        dr["AttendTimeStart"] = DateTime.Parse(tbAttendDate.Text + " " + ddlStartHour.SelectedValue + ":" + ddlStartMinute.SelectedValue + ":00");
        int extraday = 0;
        if (rpType.SelectedValue == ((int)Const.DutyType.行政值班晚上).ToString())
            extraday = 1;
        dr["AttendTimeEnd"] = DateTime.Parse(tbAttendDate.Text + " " + ddlEndHour.SelectedValue + ":" + ddlEndMinute.SelectedValue + ":00").AddDays(extraday);
        dr["IsWeekEnd"] = cbIsWeekEnd.Checked;
        dr["IsHoliday"] = cbIsholiday.Checked;
        dr["Remark2"] = rpType.SelectedItem.Text;
        dr["Remark"] = rpType.SelectedValue;
        dr["UserID"] = txtUserID.Text;
        dr["UserName"] = txtUserName.Text;
        dr["UserDisplayName"] = txtUserDisplayName.Text;
        if (!string.IsNullOrEmpty(txtOtherUserID.Text))
        {
            dr["OtherUserID"] = txtOtherUserID.Text;
            dr["OtherUserName"] = txtOtherUserDisplay.Text;
        }
        ArrayList alDeptID = new ArrayList();
        foreach (string s in txtUserID.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
        {
            alDeptID.Add(OrganizationHelper.GetUserInfo(new Guid(s)).MainDepartmentID.ToString());
        }
        dr["DepartmentID"] = string.Join(";", alDeptID.ToArray(typeof(string)) as string[]);
        dr["ID"] = Guid.NewGuid();
        ItemList.Rows.Add(dr);

        tbAttendDate.Text = string.Empty;
        ddlEndHour.SelectedIndex = 0;
        ddlEndMinute.SelectedIndex = 0;
        ddlStartHour.SelectedIndex = 0;
        ddlStartMinute.SelectedIndex = 0;
        BindRptItemList();
        rpType.SelectedValue = "";
    }
    private void BindRptItemList()
    {
        DataRow[] drs = ItemList.Select("1=1", "AttendDate");
        DataTable dt = ItemList.Clone();
        foreach (DataRow dr in drs)
        {
            dt.ImportRow(dr);
        }
        ItemList = dt;
        rptItemList.DataSource = ItemList;
        rptItemList.DataBind();
    }
    protected void lbtnSave_Click(object sender, EventArgs e)  //值班添加时，必须是上步已提交按钮触发后，再执行保存按钮
    {
        if (AttendID != 0)
        {
            foreach (DataRow dr in ItemList.Rows)
            {
                AttendenceItem attendenceItem = new AttendenceItem();
                if (dr["ID"] != DBNull.Value && dr["ID"] != null)
                {
                    attendenceItem.ID = new Guid(dr["ID"].ToString());
                    attendenceItem.Load();
                }
                else
                {
                    attendenceItem.ID = Guid.NewGuid();
                }
                attendenceItem.AttendenceID = AttendID;
                attendenceItem.AttendDate = (DateTime)dr["AttendDate"];
                attendenceItem.AttendTimeStart = (DateTime)dr["AttendTimeStart"];
                attendenceItem.AttendTimeEnd = (DateTime)dr["AttendTimeEnd"];
                attendenceItem.IsHoliday = (bool)dr["IsHoliday"];
                attendenceItem.IsWeekEnd = (bool)dr["IsWeekEnd"];
                attendenceItem.Remark = dr["Remark"].ToString();
                attendenceItem.Save();
                string[] UserID = dr["UserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserName = dr["UserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserDisplayName = dr["UserDisplayName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserDeptID = dr["DepartmentID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] OtherUserID = dr["OtherUserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] OtherUserName = dr["OtherUserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < UserID.Length; i++)
                {
                    AttendenceUser attendenceUser = new AttendenceUser();
                    attendenceUser.UserID = new Guid(UserID[i]);
                    attendenceUser.UserName = UserName[i];
                    attendenceUser.UserDisplayName = UserDisplayName[i];
                    if (i < UserDeptID.Length)
                        attendenceUser.DepartmentID = UserDeptID[i] == string.Empty ? Guid.Empty : new Guid(UserDeptID[i]);
                    attendenceUser.AttendenceItemID = attendenceItem.ID;
                    attendenceUser.UserType = UserType.Portal.ToString();
                    attendenceUser.IsReported = true;
                    attendenceUser.Save();
                    AttendenceDate date = new AttendenceDate();
                    date.AttendenceItemID = attendenceItem.ID;
                    date.UserDisplayName = UserDisplayName[i];
                    date.UserID = new Guid(UserID[i]);
                    date.Save();
                }
                for (int j = 0; j < OtherUserID.Length; j++)
                {
                    AttendenceUser attendenceUser = new AttendenceUser();
                    attendenceUser.UserID = new Guid(OtherUserID[j]);
                    attendenceUser.UserName = OtherUserName[j];
                    attendenceUser.UserDisplayName = OtherUserName[j];
                    attendenceUser.UserType = UserType.Other.ToString();
                    attendenceUser.IsReported = true;
                    attendenceUser.DepartmentID = Guid.Empty;
                    attendenceUser.AttendenceItemID = attendenceItem.ID;
                    attendenceUser.Save();
                    AttendenceDate date = new AttendenceDate();
                    date.AttendenceItemID = attendenceItem.ID;
                    date.UserDisplayName = OtherUserName[j];
                    date.UserID = new Guid(OtherUserID[j]);
                    date.Save();

                }
            }

            //从数据库中删除指定的DataTable DelItem
            BLAttendences.DeleteAttendencesItem(DelItem);
        }
        else
        {
            Attendence attendence = new Attendence();
            attendence.CreateTime = DateTime.Now.Date;
            attendence.Description = tbDescription.Text;
            attendence.Name = tbName.Text;
            attendence.Place = tbPlace.Text;
            attendence.IsShutDown = false;
            attendence.Add();
            MessagesService service = new MessagesService();
            foreach (DataRow dr in ItemList.Rows)
            {
                AttendenceItem attendenceItem = new AttendenceItem(Guid.NewGuid());
                attendenceItem.AttendenceID = attendence.ID;
                attendenceItem.AttendDate = (DateTime)dr["AttendDate"];
                attendenceItem.AttendTimeStart = (DateTime)dr["AttendTimeStart"];
                attendenceItem.AttendTimeEnd = (DateTime)dr["AttendTimeEnd"];
                attendenceItem.IsHoliday = (bool)dr["IsHoliday"];
                attendenceItem.IsWeekEnd = (bool)dr["IsWeekEnd"];
                attendenceItem.Remark = dr["Remark"].ToString();
                attendenceItem.Add();

                string[] UserID = dr["UserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserName = dr["UserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserDisplayName = dr["UserDisplayName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] UserDeptID = dr["DepartmentID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] OtherUserID = dr["OtherUserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] OtherUserName = dr["OtherUserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < UserID.Length; i++)
                {
                    AttendenceUser attendenceUser = new AttendenceUser();
                    attendenceUser.UserID = new Guid(UserID[i]);
                    attendenceUser.UserName = UserName[i];
                    attendenceUser.UserDisplayName = UserDisplayName[i];
                    attendenceUser.DepartmentID = new Guid(UserDeptID[i]);
                    attendenceUser.AttendenceItemID = attendenceItem.ID;
                    attendenceUser.IsReported = true;
                    attendenceUser.UserType = UserType.Portal.ToString();
                    attendenceUser.Add();
                    AttendenceDate date = new AttendenceDate();
                    date.AttendenceItemID = attendenceItem.ID;
                    date.UserDisplayName = UserDisplayName[i];
                    date.UserID = new Guid(UserID[i]);
                    date.Add();
                }
                for (int j = 0; j < OtherUserID.Length; j++)
                {
                    AttendenceUser attendenceUser = new AttendenceUser();
                    attendenceUser.UserID = new Guid(OtherUserID[j]);
                    attendenceUser.UserName = OtherUserName[j];
                    attendenceUser.UserDisplayName = OtherUserName[j];
                    attendenceUser.DepartmentID = Guid.Empty;
                    attendenceUser.AttendenceItemID = attendenceItem.ID;
                    attendenceUser.IsReported = true;
                    attendenceUser.UserType = UserType.Portal.ToString();
                    attendenceUser.Add();
                    AttendenceDate date = new AttendenceDate();
                    date.AttendenceItemID = attendenceItem.ID;
                    date.UserDisplayName = OtherUserName[j];
                    date.UserID = new Guid(OtherUserID[j]);
                    date.Add();
                }

            }
        }
        string script = "<script>alert('保存成功!');refreshParent();window.close();</script>";
        ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
    }

    protected void rptItemList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Delete":
                DelItem.ImportRow(ItemList.Rows[e.Item.ItemIndex]);

                ItemList.Rows.RemoveAt(e.Item.ItemIndex);    //内存中的条目删除            
                BindRptItemList();
                break;
            case "Edit":
                DataRow dr = ItemList.Rows[e.Item.ItemIndex];
                txtItemID.Value = e.Item.ItemIndex.ToString();
                ListItem li = rpType.Items.FindByValue(dr["Remark"].ToString());
                if (li != null)
                    rpType.SelectedValue = li.Value;

                tbAttendDate.Text = DateTime.Parse(dr["AttendDate"].ToString()).ToString("yyyy-MM-dd");
                if (ddlEndHour.SelectedItem != null) ddlEndHour.SelectedItem.Selected = false;
                ddlEndHour.Items.FindByText(((DateTime)dr["AttendTimeEnd"]).ToString("HH")).Selected = true;
                if (ddlEndMinute.SelectedItem != null) ddlEndMinute.SelectedItem.Selected = false;
                ddlEndMinute.Items.FindByText(((DateTime)dr["AttendTimeEnd"]).ToString("mm")).Selected = true;
                if (ddlStartHour.SelectedItem != null) ddlStartHour.SelectedItem.Selected = false;
                ddlStartHour.Items.FindByText(((DateTime)dr["AttendTimeStart"]).ToString("HH")).Selected = true;
                if (ddlStartMinute.SelectedItem != null) ddlStartMinute.SelectedItem.Selected = false;
                ddlStartMinute.Items.FindByText(((DateTime)dr["AttendTimeStart"]).ToString("mm")).Selected = true;
                cbIsholiday.Checked = (bool)dr["IsHoliday"];
                cbIsWeekEnd.Checked = (bool)dr["IsWeekEnd"];
                txtUserName.Text = dr["UserName"].ToString();

                txtUserID.Text = dr["UserID"].ToString();
                txtUserDisplayName.Text = dr["UserDisplayName"].ToString();

                txtOtherUserID.Text = dr["OtherUserID"].ToString();
                txtOtherUserDisplay.Text = dr["OtherUserName"].ToString();

                btnAddItem.Visible = false;
                btnSaveItem.Visible = true;
                break;
        }
    }
    protected void btnPLAdd_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtPLEndDate.Text) || string.IsNullOrEmpty(txtPLStartDate.Text))
        {
            ClientScript.RegisterStartupScript(GetType(), "PLaWarning", "<script>alert('必须填写批量添加的开始日期和结束日期！');</script>");
            return;
        }
        if (string.IsNullOrEmpty(txtPLUserDisplayName.Text) && string.IsNullOrEmpty(txtPLOtherUserDisplay.Text))
        {
            ClientScript.RegisterStartupScript(GetType(), "PLaWarning", "<script>alert('必须填写批量添加的值班人员！');</script>");
            return;
        }
        DateTime start = DateTime.Parse(txtPLStartDate.Text);
        DateTime end = DateTime.Parse(txtPLEndDate.Text);
        while (start <= end)
        {
            if (ddlWeek.SelectedValue == "全部" || start.DayOfWeek.ToString() == ddlWeek.SelectedValue)
            {
                DataRow dr = ItemList.NewRow();
                dr["aIndex"] = ItemList.Rows.Count + 1;
                dr["AttendDate"] = start;
                dr["UserID"] = txtPLUserID.Text;
                dr["UserName"] = txtPLUserName.Text;
                dr["UserDisplayName"] = txtPLUserDisplayName.Text;

                if (!string.IsNullOrEmpty(txtPLOtherUserID.Text))
                {
                    dr["OtherUserID"] = txtPLOtherUserID.Text;
                    dr["OtherUserName"] = txtPLOtherUserDisplay.Text;
                }
                ArrayList alDeptID = new ArrayList();
                foreach (string s in txtPLUserID.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    alDeptID.Add(OrganizationHelper.GetUserInfo(new Guid(s)).MainDepartmentID.ToString());
                }
                dr["DepartmentID"] = string.Join(";", alDeptID.ToArray(typeof(string)) as string[]);

                dr["IsWeekEnd"] = start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday;
                DateTime temp = start;

                int extra = 0;
                if (start.Month >= 5 && start.Month <= 9)
                    extra = 30;
                if (rpType2.SelectedValue == ((int)Const.DutyType.行政值班白天).ToString() || rpType2.SelectedValue == ((int)Const.DutyType.大厅值班).ToString() || rpType2.SelectedValue == ((int)Const.DutyType.戬浜值班).ToString())
                {
                    dr["AttendTimeStart"] = temp.AddHours(8);
                    dr["AttendTimeEnd"] = temp.AddHours(16).AddMinutes(30 + extra);
                }
                if (rpType2.SelectedValue == ((int)Const.DutyType.行政值班晚上).ToString())
                {
                    dr["AttendTimeStart"] = temp.AddHours(16).AddMinutes(30 + extra);
                    dr["AttendTimeEnd"] = temp.AddDays(1).AddHours(8);
                }
                if (rpType2.SelectedValue == ((int)Const.DutyType.节假日上午).ToString())
                {
                    dr["AttendTimeStart"] = temp.AddHours(8);
                    dr["AttendTimeEnd"] = temp.AddHours(12);
                }
                if (rpType2.SelectedValue == ((int)Const.DutyType.节假日下午).ToString())
                {
                    dr["AttendTimeStart"] = temp.AddHours(12);
                    dr["AttendTimeEnd"] = temp.AddHours(16).AddMinutes(30 + extra);
                }
                //Holiday d = new Holiday(start);
                //if (d.Load())
                dr["IsHoliday"] = cbIsHoliday2.Checked;
                //else
                //    dr["IsHoliday"] = false;
                dr["Remark"] = rpType2.SelectedValue;
                dr["Remark2"] = rpType2.SelectedItem.Text;
                dr["ID"] = Guid.NewGuid();
                ItemList.Rows.Add(dr);
            }
            start = start.AddDays(1);
        }
        BindRptItemList();
        rpType2.SelectedValue = "";
    }
    protected void btnSaveItem_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtItemID.Value))
        {
            ClientScript.RegisterStartupScript(GetType(), "PLaWarning", "<script>alert('保存意外终止！');</script>");
            return;
        }
        if (string.IsNullOrEmpty(txtUserDisplayName.Text) && string.IsNullOrEmpty(txtOtherUserDisplay.Text))
        {
            ClientScript.RegisterStartupScript(GetType(), "PLaWarning", "<script>alert('必须填写值班人员！');</script>");
            return;
        }
        DataRow dr = ItemList.Rows[int.Parse(txtItemID.Value)];
        dr["AttendDate"] = DateTime.Parse(tbAttendDate.Text);
        dr["AttendTimeStart"] = DateTime.Parse(tbAttendDate.Text + " " + ddlStartHour.SelectedValue + ":" + ddlStartMinute.SelectedValue + ":00");

        int extraday = 0;
        if (rpType.SelectedValue == ((int)Const.DutyType.行政值班晚上).ToString())
            extraday = 1;
        dr["AttendTimeEnd"] = DateTime.Parse(tbAttendDate.Text + " " + ddlEndHour.SelectedValue + ":" + ddlEndMinute.SelectedValue + ":00").AddDays(extraday);
        dr["IsWeekEnd"] = cbIsWeekEnd.Checked;
        dr["IsHoliday"] = cbIsholiday.Checked;
        dr["Remark"] = rpType.SelectedValue;
        dr["Remark2"] = rpType.SelectedItem.Text;
        dr["UserID"] = txtUserID.Text;
        dr["UserName"] = txtUserName.Text;
        dr["UserDisplayName"] = txtUserDisplayName.Text;


        dr["OtherUserID"] = txtOtherUserID.Text;
        dr["OtherUserName"] = txtOtherUserDisplay.Text;

        ArrayList alDeptID = new ArrayList();
        foreach (string s in txtUserID.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
        {
            User u = OrganizationHelper.GetUserInfo(new Guid(s));
            if (u != null)
            {
                alDeptID.Add(u.MainDepartmentID.ToString());
            }
        }
        dr["DepartmentID"] = string.Join(";", alDeptID.ToArray(typeof(string)) as string[]);


        tbAttendDate.Text = string.Empty;
        ddlEndHour.SelectedIndex = 0;
        ddlEndMinute.SelectedIndex = 0;
        ddlStartHour.SelectedIndex = 0;
        ddlStartMinute.SelectedIndex = 0;

        BindRptItemList();
        btnAddItem.Visible = true;
        btnSaveItem.Visible = false;
        rpType.SelectedValue = "";
    }
    protected void btnDelPlan_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < rptItemList.Items.Count; i++)
        {
            RepeaterItem item = rptItemList.Items[i];
            CheckBox cb = item.FindControl("cbItem") as CheckBox;
            HiddenField hid = item.FindControl("hidItem") as HiddenField;
            if (cb.Checked)
            {
                ItemList.Select("aIndex=" + hid.Value)[0].Delete();
            }
        }
        BindRptItemList();
    }
    public string getReceiver(string userName, string userDisplayName, string Mobile)
    {
        return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
                                    <Receivers>
  			                                   <Receiver>
    				                                    <Name>{0}</Name>
    				                                    <DisplayName>{1}</DisplayName>
    				                                    <NodeType>User</NodeType>
    				                                    <Email></Email>
    				                                    <LCS></LCS>
    				                                    <Mobile>{2}</Mobile>
    				                                    <Fax></Fax>
  			                                    </Receiver>
                                    </Receivers>", userName, userDisplayName, Mobile);
    }
    private string getProperty(Property[] propertys, string PropertyName)
    {
        foreach (Property p in propertys)
        {
            if (p.Name == PropertyName)
            {
                return p.Data.ToString();
            }
        }
        return string.Empty;
    }
    private string ModuleID
    {
        get
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.Guid"">{0}</value>", ConfigurationManager.AppSettings["ModuleID"]);
        }
    }
    private string SendTime
    {
        get
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.DateTime"">{0}</value>", DateTime.Now);
        }
    }
    private string SenderName
    {
        get
        {
            return ConfigurationManager.AppSettings["SenderName"];
        }
    }
    protected void lbtnSendMsg_Click(object sender, EventArgs e)
    {
        MessagesService service = new MessagesService();
        foreach (DataRow dr in ItemList.Rows)
        {
            string[] UserID = dr["UserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] UserName = dr["UserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] UserDisplayName = dr["UserDisplayName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] UserDeptID = dr["DepartmentID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] OtherUserID = dr["OtherUserID"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] OtherUserName = dr["OtherUserName"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < UserID.Length; i++)
            {
                Property[] properties = OrganizationHelper.GetPropertyInfoListByUsers(new Guid[] { new Guid(UserID[i]) }, new string[] { "Mobile" });
                string Mobile = getProperty(properties, "Mobile");
                string msg = string.Format("{0:yyyy年MM月dd日 HH:mm}至{1:HH:mm}在{2}值班", (DateTime)dr["AttendTimeStart"], (DateTime)dr["AttendTimeEnd"], tbPlace.Text);
                if (!string.IsNullOrEmpty(Mobile))
                {

                    service.SendMessageByModuleID(ModuleID, SenderName, getReceiver(UserName[i], UserDisplayName[i], Mobile), msg, msg, false, 1, string.Empty, SendTime);
                }
            }
            for (int j = 0; j < OtherUserID.Length; j++)
            {
                OtherUser u = new OtherUser(new Guid(OtherUserID[j]));
                u.Load();
                string msg = string.Format("{0:yyyy年MM月dd日 HH:mm}至{1:HH:mm}在{2}值班", (DateTime)dr["AttendTimeStart"], (DateTime)dr["AttendTimeEnd"], tbPlace.Text);
                service.SendMessageByModuleID(ModuleID, SenderName, getReceiver(OtherUserName[j], OtherUserName[j], u.Mobile), msg, msg, false, 1, string.Empty, SendTime);
            }

        }
    }
}
